Imports Microsoft.VisualBasic
Imports System.ComponentModel
Imports System.Web.UI
Imports System.Text
Imports System.Web.UI.WebControls


Namespace WebControls


    <ToolboxData("<{0}:MaskTextBox runat=""server""></{0}:MaskTextBox>")> _
        Public Class MaskTextBox
        Inherits TextBox

        Private mAddRequireValidator As Boolean = False
        Private requireValidator As RequiredFieldValidator

        Private mAddExpressValidator As Boolean = False
        Private expressValidator As RegularExpressionValidator

        Private mValidatorCss As String = "validator"
        Private mTextMaskType As MaskType = MaskType.None
        Private mLessZero As Boolean = False

#Region "Properties"
        Public Property LessZero() As Boolean
            Get
                Return mLessZero
            End Get
            Set(ByVal value As Boolean)
                mLessZero = value
            End Set
        End Property

        <Description("Auto add RequiredFieldValidator  ")> _
          Public Property AddRequireValidator() As Boolean
            Set(ByVal value As Boolean)
                mAddRequireValidator = value
            End Set
            Get
                Return mAddRequireValidator
            End Get
        End Property

        <Description("Auto add RegularExpressionValidator ")> _
        Public Property AddExpressValidator() As Boolean
            Set(ByVal value As Boolean)
                mAddExpressValidator = value
            End Set
            Get
                Return mAddExpressValidator
            End Get
        End Property

        <DefaultValue("")> _
        Public Property TextMaskType() As MaskType
            Set(ByVal value As MaskType)
                mTextMaskType = value
            End Set
            Get
                Return mTextMaskType
            End Get
        End Property

        <DefaultValue("")> _
        Public Property RequiredErrorMessage() As String
            Get
                Me.EnsureChildControls()
                Return Me.requireValidator.ErrorMessage
            End Get
            Set(ByVal value As String)
                Me.EnsureChildControls()
                Me.requireValidator.ErrorMessage = value
            End Set
        End Property

        <DefaultValue("")> _
        Public Property ExpressionErrorMessage() As String
            Get
                Me.EnsureChildControls()
                Return expressValidator.ErrorMessage
            End Get
            Set(ByVal value As String)
                Me.EnsureChildControls()
                expressValidator.ErrorMessage = value
            End Set
        End Property

        <DefaultValue("")> _
        Public Property ValidationExpression() As String
            Get
                Me.EnsureChildControls()
                Return expressValidator.ValidationExpression
            End Get
            Set(ByVal value As String)
                Me.EnsureChildControls()
                expressValidator.ValidationExpression = value
                Me.mTextMaskType = MaskType.Custom
            End Set
        End Property

        Public Property ValidatorCss() As String
            Get
                Return mValidatorCss
            End Get
            Set(ByVal value As String)
                mValidatorCss = value
            End Set
        End Property

#End Region

        Protected Overrides Sub CreateChildControls()
            Controls.Clear()
            requireValidator = New RequiredFieldValidator
            requireValidator.ID = MyBase.ID + "_reqValidator"
            requireValidator.ControlToValidate = Me.ID
            requireValidator.ValidationGroup = ValidationGroup
            requireValidator.CssClass = mValidatorCss
            'requireValidator.ErrorMessage = "This field should not be empty."
            Controls.Add(requireValidator)

            expressValidator = New RegularExpressionValidator
            expressValidator.ID = MyBase.ID + "_expValidator"
            expressValidator.ControlToValidate = Me.ID
            expressValidator.ValidationGroup = ValidationGroup
            expressValidator.CssClass = mValidatorCss
            If Not mTextMaskType = MaskType.Custom Then expressValidator.ValidationExpression = RegexString()
            'expressValidator.ErrorMessage = "Invalid input."
            Controls.Add(expressValidator)

            Me.ChildControlsCreated = True
            'MyBase.CreateChildControls()
        End Sub

        Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
            MyBase.Render(writer)
            If Not Me.DesignMode Then
                If Me.mAddRequireValidator Then
                    requireValidator.RenderControl(writer)
                End If

                If Me.mAddExpressValidator Then
                    expressValidator.RenderControl(writer)
                End If
            End If
        End Sub

        Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
            Select Case mTextMaskType
                Case MaskType.Currency
                    Me.Attributes.Add("onpaste", "return false;")
            End Select

            requireValidator.Display = ValidatorDisplay.Dynamic
            expressValidator.Display = ValidatorDisplay.Dynamic

            If Me.mTextMaskType = MaskType.Currency OrElse Me.mTextMaskType = MaskType.Number Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, Page.GetType(), "checkTextBox", GetJs, False)
                Dim js As String = String.Format("TextValueChange(this,event,'{0}','{1}');", mTextMaskType.ToString, mLessZero)
                Me.Attributes.Add("onkeypress", js)

                If Me.mTextMaskType = MaskType.Currency Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, Page.GetType, "txtOnBlur", GetBlurJs, False)
                    Me.Attributes.Add("onblur", "txtBlur(this);")
                End If
            End If
        End Sub

        Private Function RegexString() As String
            Select Case TextMaskType
                Case MaskType.Custom
                    Return ""
                Case MaskType.Currency
                    If mLessZero Then Return "(^\-?[1-9]\d*(\.\d{1,3})?$)|(^\-?0\.(([0-9]{1,3})|(\-?\d{1}[1-9])|(\-?[1-9]\d{1}))$)"
                    Return "(^[1-9]\d*(\.\d{1,3})?$)|(^0\.(([0-9]{1,3})|(\d{1}[1-9])|([1-9]\d{1}))$)"
                Case MaskType.Email
                    Return "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                Case MaskType.Number
                    Return "^\d*$"
                Case MaskType.NumberString
                    Return "^\w*$"
            End Select
            Return ""
        End Function

        Private Function GetJs() As String
            Dim js As String = "<script type=""text/javascript"">function TextValueChange(obj,e,maskType,isLessZero){var txtval=obj.value;var key = document.all ? e.keyCode : e.charCode;switch (maskType){   case ""Currency"":if((key < 48||key > 57)&&key != 46&&(key!=45)){document.all ? e.keyCode = 0 :  e.preventDefault();}else{if(key == 46){if(txtval.indexOf('.') != -1||txtval.length == 0)document.all ? e.keyCode = 0 :  e.preventDefault();}else if(key == 45){if( isLessZero=='False' || txtval.indexOf('-') != -1  ) document.all ? e.keyCode = 0 :  e.preventDefault();}break;}case ""Number"":if((key < 48||key > 57)&&key!=45){document.all ? e.keyCode = 0 :  e.preventDefault();}else if(key == 45){if( isLessZero=='False' || txtval.indexOf('-') != -1  ) document.all ? e.keyCode = 0 :  e.preventDefault();break;}}}</script> "
            Return js
        End Function

        Private Function GetBlurJs() As String
            Return "<script type=""text/javascript"" >function txtBlur(obj){var value=obj.value;if(value==0){value="""";}if(value.indexOf('-') != 0){value = value.replace(""-"","""");}obj.value=value;}</script>"
        End Function

        Public Enum MaskType
            None = 0
            Currency
            Number
            NumberString
            Email
            Custom
        End Enum

    End Class

End Namespace

